package top.kaoshanji.q1ch07c;

import top.kaoshanji.y1constant.FileConstant;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-q1ch07c-341页a：从流中得到通道
 * 代码很细节
 * author kaoshanji
 * ^_^
 * create time 2025/3/12 17:59
 */
public class GetChannel {

    static String pathStr = FileConstant.LOCAL_ROOT_PATH.concat("q1ch07c341页a\\data.txt");
    static final int BSIZE = 1024;

    public static void main(String[] args) {

        // 写文件
        try (FileChannel fileChannel = new FileOutputStream(pathStr).getChannel()){
            // 创建 ByteBuffer 的一种方式：已经有数据
            fileChannel.write(ByteBuffer.wrap("我是靓仔".getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        // 添加到文件末尾
        try (FileChannel fileChannel = new RandomAccessFile(pathStr, "rw").getChannel()){
            fileChannel.position(fileChannel.size()); // 移动到末尾
            fileChannel.write(ByteBuffer.wrap("，更进一步".getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        // 读文件
        try (FileChannel fileChannel = new FileInputStream(pathStr).getChannel()){

            // 创建 ByteBuffer 的一种方式：有个对象，没有数据
            ByteBuffer buffer = ByteBuffer.allocate(BSIZE);
            fileChannel.read(buffer);
            buffer.flip();

            while (buffer.hasRemaining()) {
                System.out.write(buffer.get());
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        System.out.flush();

    }



}
